<template>
  <el-form-item :label="name" :prop="code">
    <el-popover
      placement="bottom-start"
      trigger="focus"
    >
      <!--   开窗中内容   -->
      <template #default>
        <!--    已选择的 标签    -->
        <div class="flex flex-row align-center mb-10 tag-wrapper">
          <span class="font-bold mb-5">已选：</span>
          <el-tag
            v-for="tag in labels"
            :key="tag.id"
            class="mb-5"
            size="small"
            closable
            :disable-transitions="false"
            @close="handleMoveTag(tag)"
          >
            {{ tag.name }}
          </el-tag>
        </div>
        <!--    搜索框    -->
        <el-input
          v-model="searcher.name"
          class="mb-10"
          placeholder="请输入内容,按回车搜索"
          prefix-icon="el-icon-search"
          @change="handleEnter"
        />
        <!--    检索表格    -->
        <el-table
          ref="multipleTable"
          v-loading="loading"
          class="mb-10"
          :data="data"
          tooltip-effect="dark"
          row-key="code"
          style="width: 100%"
          @selection-change="handleSelectChange"
        >
          <el-table-column
            type="selection"
            width="55"
            :reserve-selection="true"
          />
          <el-table-column
            label="code"
            width="120"
            prop="code"
          />
          <el-table-column
            prop="name"
            label="名称"
            width="120"
          />
        </el-table>
        <el-pagination
          background
          layout="prev, pager, next ,total"
          :current-page.sync="pagination.pageNo"
          :page-size="pagination.pageSize"
          :total="pagination.total"
          @current-change="pageChange"
        />
      </template>
      <!--   触发组件   -->
      <template #reference>
        <el-input size="small" class="item">
          <template v-if="labels" #prefix>
            <div v-if="labels.length>0" class="flex flex-row align-center" style="height: 38px">
              <el-tag v-show="labels.length>0" style="margin:2px 0 2px 6px" type="info" size="small">
                {{ labels[0].name }}
              </el-tag>
              <el-tag v-show="labels.length>1" style="margin:2px 0 2px 6px" size="small" type="info">
                +{{ labels.length - 1 }}
              </el-tag>
            </div>
          </template>
        </el-input>
      </template>
    </el-popover>
  </el-form-item>
</template>

<script>
import { findPage } from '@/api/ik/data/dataApi'

export default {
  props: {
    url: { type: String, default: 'health/content/label/contentlabel' }, // API请求的URL
    value: { type: [String, null], default: "[]" }, // 默认的选中标签
    name: { type: String, default: "" },
    dataDown: { type: Boolean, default: false },
    code: { type: String, default: "" }
  },
  data() {
    return {
      labels: [], // 已选择的标签
      activeTags: [], // 当前表格中选中的标签
      loading: false, // 表格加载状态
      searcher: { name: '' }, // 搜索框内容
      data: [], // 表格数据
      pagination: { pageSize: 5, pageNo: 1, total: 0 }, // 分页信息
      initLabel: false
    }
  },
  watch: {
    dataDown() {
      this.init()
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    /**
     * 按回车搜索
     */
    handleEnter() {
      this.getData()
    },
    // 获取表格数据
    getData(page = 1) {
      this.loading = true // 开始加载数据
      findPage(this.url, this.searcher, this.pagination.pageSize, page)
        .then(res => {
          this.pagination.total = res.data.totalCount // 设置总条数
          this.data = res.data.list // 设置表格数据
          if (this.labels) {
            this.syncSelectData() // 同步选中标签
          }
        })
        .finally(() => {
          this.loading = false
        }) // 结束加载数据
    },

    // 处理表格选择变化
    handleSelectChange(tags) {
      if (!this.initLabel) {
        this.labels = this.activeTags = [...tags] // 更新已选择标签和当前选中的标签
        this.$emit("input", JSON.stringify(this.labels))
      } else {
        this.activeTags = [...tags]
      }
    },

    // 删除已选择标签
    handleMoveTag(tag) {
      this.labels = this.labels.filter(t => t !== tag) // 从已选择标签中移除指定标签
      this.$refs.multipleTable.toggleRowSelection(tag, false) // 取消表格中对应行的选中状态
    },

    // 翻页
    pageChange(page) {
      this.getData(page) // 请求对应页的数据
    },

    // 同步选中标签与表格数据
    syncSelectData() {
      const labels = this.activeTags.map(tag => tag.name) // 获取已选择标签的名称数组
      if (this.data) {
        this.data.forEach(item => {
          // 根据标签是否在已选择标签或默认值中，设置表格中对应行的选中状态
          if (!labels.includes(item.name)) {
            const labelsName = this.labels.map(label => label.name)
            if (this.$refs.multipleTable) {
              this.$refs.multipleTable.toggleRowSelection(item, labelsName.includes(item.name))
            }
          }
        })
      }
    },

    /**
     * 初始化数据
     */
    init() {
      try {
        this.labels = this.value === null ? [] : this.value
        this.labels = JSON.parse(this.value)
      } catch (err) {
        this.labels = []
      }
      this.initLabel = true
      if (this.labels) {
        this.labels.forEach((item) => {
          this.$refs.multipleTable.toggleRowSelection(item, true)
        })
      }
      this.initLabel = false
      this.getData() // 组件挂载后获取数据
    }
  }
}
</script>

<style scoped>
::v-deep.require > .el-input__inner {
  border: red 1px solid;
}

.item {
  width: calc(100% - 30px)
}
</style>
<style lang="scss" scoped>
.tag-wrapper {
  min-height: 24px;
  max-width: 295px;
  flex-wrap: wrap;
}

.el-form-item {
  margin-bottom: 12px;
  width: 100%;
}

.el-form-item__label {
  width: 180px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.el-form-item__content {
  width: calc(100% - 180px);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
